package com.easy.app.controller.system;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.easy.framework.common.model.R;
import com.easy.framework.common.utils.StringUtil;
import com.easy.framework.common.validate.Add;
import com.easy.framework.common.validate.Update;
import com.easy.framework.security.utils.SecurityUtils;
import com.easy.framework.web.base.BaseController;
import com.easy.module.log.annotation.Log;
import com.easy.module.log.enums.Operation;
import com.easy.module.system.entity.SysMenu;
import com.easy.module.system.enums.MenuType;
import com.easy.module.system.query.SysMenuQuery;
import com.easy.module.system.service.ISysMenuService;
import com.easy.framework.common.model.TreeModel;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 菜单信息
 *
 * @author easy
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {
    private final ISysMenuService sysMenuService;

    /**
     * 获取菜单列表
     */
    @PreAuthorize("@perm.hasPermission('system:menu$list')")
    @GetMapping("/list")
    public R<List<SysMenu>> list(SysMenuQuery query) {
        return R.success(sysMenuService.listByUserId(query, SecurityUtils.getUserId()));
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("@perm.hasPermission('system:menu$query')")
    @GetMapping(value = "/{menuId}")
    public R<SysMenu> get(@PathVariable("menuId") Long menuId) {
        return R.success(sysMenuService.getById(menuId));
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@perm.hasPermission('system:menu$add')")
    @Log(title = "菜单管理", type = Operation.INSERT)
    @PostMapping
    public R add(@Validated({Add.class}) @RequestBody SysMenu menu) {
        if (menu.getIsFrame() && !StringUtil.ishttp(menu.getPath())) {
            return R.fail("新增菜单'" + menu.getName() + "'失败，地址必须以http(s)://开头");
        }
        return R.result(sysMenuService.add(menu));
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@perm.hasPermission('system:menu$edit')")
    @Log(title = "菜单管理", type = Operation.UPDATE)
    @PutMapping
    public R edit(@Validated({Update.class}) @RequestBody SysMenu menu) {
        if (menu.getIsFrame() && !StringUtil.ishttp(menu.getPath())) {
            return R.fail("修改菜单'" + menu.getName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getId().equals(menu.getParentId())) {
            return R.fail("修改菜单'" + menu.getName() + "'失败，上级菜单不能选择自己");
        }
        return R.result(sysMenuService.update(menu));
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@perm.hasPermission('system:menu$remove')")
    @Log(title = "菜单管理", type = Operation.DELETE)
    @DeleteMapping("/{menuId}")
    public R remove(@PathVariable("menuId") Long menuId) {
        if (sysMenuService.hasChildByMenuId(menuId)) {
            return R.fail("存在子菜单,不允许删除");
        }
        if (sysMenuService.hasRoleByMenuId(menuId)) {
            return R.fail("菜单已分配,不允许删除");
        }
        return R.result(sysMenuService.deleteById(menuId));
    }

    /**
     * 获取菜单列表
     */
    @PreAuthorize("@perm.hasPermission('system:menu$list')")
    @GetMapping("/children")
    public R<List<SysMenu>> children(SysMenuQuery query) {
        return R.success(sysMenuService.children(query, SecurityUtils.getUserId()));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public R<List<TreeModel>> treeselect(SysMenuQuery query) {
        List<SysMenu> menus = sysMenuService.listByUserId(query, SecurityUtils.getUserId());
        return R.success(sysMenuService.treeList(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/treeselect/{roleId}")
    public R roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysMenu> menus = sysMenuService.listByUserId(null,SecurityUtils.getUserId());
        Map<String, Object> data = new HashMap<>();
        data.put("checkedKeys", sysMenuService.getMenuIdListByRoleId(roleId));
        data.put("menus", sysMenuService.treeList(menus));
        return R.success(data);
    }



    /**
     * 根据菜单路由获取详细信息
     */
    @PreAuthorize("@perm.hasAnyPermission('system:menu$query','xcode:page$menu')")
    @GetMapping(value = "/page/{pageId}")
    public R<SysMenu> getByPageId(@PathVariable("pageId") String pageId) {
        return R.success(sysMenuService.getOne(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getPageId, pageId).eq(SysMenu::getType, MenuType.XCODE.getCode()),false));
    }
}